package ace.cmp.spring.graphql.core.controller;

import ace.cmp.i18n.api.AceMessageSource;
import ace.cmp.security.api.exception.ForbiddenI18nException;
import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.graphql.data.method.annotation.GraphQlExceptionHandler;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * @author caspar
 * @date 2023/9/5 14:45
 */
@ControllerAdvice
public class GraphqlExceptionController {
  private final AceMessageSource messageSource;

  public GraphqlExceptionController(AceMessageSource messageSource) {
    this.messageSource = messageSource;
  }

  @GraphQlExceptionHandler
  public GraphQLError exceptionHandler(
      ForbiddenI18nException ex, DataFetchingEnvironment environment) {
    String message =
        this.messageSource.getMessage(ex.getI18nCode(), ex.getArgs(), ex.getDefaultMessage());
    GraphQLError error =
        GraphqlErrorBuilder.newError(environment)
            .errorType(ErrorType.FORBIDDEN)
            .message(message)
            .build();
    return error;
  }
}
